package week4.day23;

import java.io.*;
import java.util.Arrays;

/**
 * @Author fengzihao
 * @Date 2024-05-07 19:14
 */
public class ReadAndeSortAndWriter {
    public static void main(String[] args) throws IOException {
        sortByIOStream(new File("a.txt"));
        sortByReaderAndWriter(new File("a.txt"));
    }

    private static void sortByReaderAndWriter(File file) throws IOException {
        FileReader fileReader = new FileReader(file);
        char[] chars = new char[1024];
        int count = fileReader.read(chars);
        Arrays.sort(chars,0,count);
        FileWriter fileWriter = new FileWriter(file,true);
        fileWriter.write("\n");
        fileWriter.write(chars,0,count);
        fileReader.close();
        fileWriter.close();
    }

    private static void sortByIOStream(File file) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int count = fileInputStream.read(bytes);
        String str = new String(bytes,0,count);
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        String strSorted = new String(chars);
        FileOutputStream fileOutputStream = new FileOutputStream(file,true);
        fileOutputStream.write("\n".getBytes());
        fileOutputStream.write(strSorted.getBytes());
        fileInputStream.close();
        fileOutputStream.close();
    }
}
